package com.game.config.quartz;

import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import com.game.config.dao.JdbcUtils;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;

import javax.annotation.Resource;
import java.sql.Date;
import java.time.LocalDate;
import java.io.File;
import java.util.Map;

@Slf4j
@Service
public class QuartzServiceImpl implements IQuartzService {
    @Resource
    private JdbcUtils jdbcUtils;
    private final String resourcePath = System.getProperty("user.dir") + "/src/main/resources";

    @Override
    public void mysqlBackupTask() {
        log.info("======执行定时器:定时备份数据库=======");
        String backUpPath = resourcePath + "/sql/" + java.sql.Date.valueOf(LocalDate.now());
        File backUpFile = new File(backUpPath);
        if (!backUpFile.exists()) {
            boolean res = backUpFile.mkdirs();
            if (!res) {
                log.info("======创建备份目录失败=======");
                return;
            }
        }


        Map<String, DataSourceProperty> dataSourceProperty = jdbcUtils.getDataSourceProperty();
        dataSourceProperty.forEach((dataName, info) -> {
            StringBuilder backSql = new StringBuilder();
            File dataFile = new File(backUpPath + "/" + dataName + System.currentTimeMillis() + ".sql");
            log.info("========开始备份数据源:{}======", dataName);
            backSql.append("mysqldump");
            backSql.append(" -u").append(info.getUsername());
            backSql.append(" -p").append(info.getPassword());
            backSql.append(" ").append(info.getData()).append(" > ");
            backSql.append(dataFile);
            log.info("======数据库备份cmd命令为：{}=======", backSql);
            try {
                Process exec = Runtime.getRuntime().exec("cmd /c" + backSql);
                if (exec.waitFor() == 0) {
                    log.info("======数据库备份成功，路径为：{}=======", dataFile);
                }
            } catch (Exception e) {
                log.error("======数据库备份失败，异常为：{}=======", e.getMessage());
            }
        });
    }

    @Override
    public void removeMysqlBackupTask() {
        log.info("======执行定时器:定时删除备份数据库文件=======");
        String backUpPath = resourcePath + "/sql";
        File backUpFile = new File(backUpPath);
        if (backUpFile.exists()) {
            File[] files = backUpFile.listFiles();
            assert files != null;
            for (File file : files) {
                if (file.isDirectory()) {
                    Date date1 = Date.valueOf(file.getName());
                    Date date2 = Date.valueOf(LocalDate.now());
                    long betweenDay = DateUtil.between(date1, date2, DateUnit.DAY);
                    if (betweenDay > 7) {
                        File[] subFiles = file.listFiles();
                        assert subFiles != null;
                        for (File subFile : subFiles) {
                            boolean delete = subFile.delete();
                        }
                        boolean delete = file.delete();
                    }
                }
            }
        }
    }
}
